from django import forms
#from store.models import applyValidators
from django.forms import ModelForm
from django.forms.widgets import HiddenInput
from pdb import Pdb
from django.db import models
class Item(models.Model):
    id = models.AutoField(primary_key=True)
    description = models.TextField(blank=True)
    price = models.FloatField()
    short_description = models.CharField(max_length=135, blank=True)
    main_show_case=models.ImageField(upload_to='photo',blank=True)
    def __unicode__(self):
        return self.description
    class Meta:
        db_table = u'item'
        
from django.contrib.auth.models import User as dj_user   
class Cart(models.Model):
    id = models.AutoField(primary_key=True)
    items=models.ManyToManyField(Item,through="Carthasitem")
    date=models.DateTimeField(blank=True)
    # this cart may belong to an annonymous user
    user=models.ForeignKey(dj_user,db_column='user',blank=True, null=True)
    def is_empty(self):
        if 0 < Carthasitem.objects.filter(cart=self).count():
            return False
        return True
    class Meta:
        db_table = u'cart'      
        
        
        
class Carthasitem(models.Model):
    cart = models.ForeignKey(Cart, db_column='cart')
    item = models.ForeignKey(Item, db_column='item')
    number = models.IntegerField()
    id = models.AutoField(primary_key=True)
    date = models.DateField(null=True, blank=True)
    class Meta:
        db_table = u'carthasitem'

#@applyValidators
class BuyItemForm(forms.ModelForm):
    class Meta:
        model=Carthasitem
        fields=('number',)
    

# Make sure the the quantity is set and is not negative 
#@applyValidators
class ChangeNumberForm(forms.ModelForm):
    class Meta:
        model=Carthasitem
        fields=('date','number')

class Cart_Context():
    def __init__(self,cart):
        self.cart=cart
        
    
    def get_context_for_cart(self):
        newlist=[]
        pdb=Pdb()
        for item in self.cart.items.all():
            price=item.price
            number=Carthasitem.objects.filter(cart=self.cart,item=item)[0].number
            main_show_case=item.main_show_case

            
            newlist.append((BuyItemForm(instance=Carthasitem.objects.filter(cart=self.cart,item=item)[0]),
                            item,
                            int(number)*price,
                            Carthasitem.objects.filter(cart=self.cart,item=item)[0].cart.pk,
                            main_show_case
                            ))              
        total=0
        for x in newlist:
            total+=x[2]
            
        return newlist

